const {
	add,
	del,
	edit,
	search,
	searchBy,
	aggregation
} = require('../js/mysql.js');

let jwt = require('jsonwebtoken');

const router = require('koa-router')()

// 登录接口
router.post('/login', async function (ctx, next) {
	let {
		body
	} = ctx.request;
	//   console.log(body);
	let {
		phone,
		psd
	} = body;
	//   console.log(phone, psd);
	let data = await searchBy('users', `name='${phone}' and password='${psd}'`);
	// console.log(data);
	if (data.length) {
		let token = jwt.sign(body, 'mengxiaodai', {
			expiresIn: 60 * 60 * 24
		})
		ctx.body = {
			token,
			msg: "登录成功",
			code: 200,
			data
		}
	} else {
		ctx.body = {
			msg: '用户名或密码错误',
			code: 520
		}
	}

})

// 注册接口
// 创建账号
router.post('/register', async function (ctx, next) {
	let {
		body
	} = ctx.request;
	// 对密码进行加密
	let {
		phone,
		pass
	} = body;
	let num = await searchBy(`users`, `name='${phone}'`);
	console.log(num);
	if (num.length===0) {
		// 存入数据库
		let data = await add([phone, pass], `users(name,password) VALUES(?,?)`);
		ctx.body = {
			msg: '注册成功',
			code: 200,
			data
		}
	} else {
		ctx.body = {
			msg: '注册失败，用户已存在',
			code: 521,
		}
	}
})

router.prefix('/users');



module.exports = router